#include <iostream>
#include <stdio.h>
using namespace std;
int p;
struct node {
    int x, y, w;
    node(int aa, int bb, int ww) {x=aa; y=bb; w=ww; }
    node() {}
    node operator*(const node& a) {
        return node((x*a.x+y*a.y%p*w)%p, (x*a.y+a.x*y)%p, a.w);
    }
};
node FastPOW(node a, int k) {
    node ret = node(1, 0, a.w);
    while (k) {
        if (k&1) {
            ret = ret * a;
        }
        k = (k>>1);
        a = (a*a);
    }
    return ret;
}
int FastPOW(int a, int k) {
    int ret = 1;
    while (k) {
        if(k&1) {
            ret = ret * a % p;
        }
        k = (k>>1);
        a = (a*a) % p;
    }
    return ret;
}
int dle(int a) {
    int k=(p-1)/2;
    int x = FastPOW(a, k);
    if (x != 1) return -1;
    return x;
}
int getW(int a, int &t) {
    int w;
    do {
        t = rand() % p;
        w = (t*t - a) % p;
        w = (w + p) % p;
//        printf("-------\n");
    }while(dle(w)==1);
    return w;
}
int solve(int a, int n) {
    if (n==2) return 1;
    int y;
    int w = getW(a, y);
    node t = node(y, 1, w);
    t = FastPOW(t, (p+1)>>1);
    return t.x;
}

int main() {
#ifdef hai
    freopen("in.txt", "r", stdin);
#endif
    int k;
    int a,n;
    cin>>k;
    while (k--) {
        scanf("%d %d", &a, &n);
//        a %= n;
        p = n;
        if (dle(a) == -1) {
            printf("No root\n");
            continue;
        }
        int x = solve(a, n);
        int y = n-x;
        if (x>y) swap(x, y);
        if (x!=y) printf("%d %d\n", x, y);
        else printf("%d\n", x);
    }
    return 0;
}
